package com.usian.service.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.usian.articles.Articles;
import com.usian.config.AliPay;
import com.usian.certified.Certified;
import com.usian.config.JwtUtil;
import com.usian.money.Money;
import com.usian.order.Order;
import com.usian.service.UserService;
import com.usian.transaction.Transaction;
import com.usian.user.User;
import com.usian.vo.Result;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class UserServiceImpl implements UserService {

    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private com.usian.mapper.UserMapper userMapper;


    @Override
    public Boolean sendMessage(String phone, String templateCode, String code) {
        /**
         * 连接阿里云：
         *
         * 三个参数：
         * regionId 不要动，默认使用官方的
         * accessKeyId 自己的用户accessKeyId
         * accessSecret 自己的用户accessSecret
         */
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        // 构建请求：
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");

        // 自定义参数：
        request.putQueryParameter("PhoneNumbers", phone);// 手机号
        request.putQueryParameter("SignName", "积云");// 短信签名
        request.putQueryParameter("TemplateCode", templateCode);// 短信模版CODE

        // 构建短信验证码
        request.putQueryParameter("TemplateParam", code);

        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Result logon(User user) {
        // 查询用户是否已注册
        User user2 = userMapper.selectUserOne(user);
        if (user2 != null) {
            return Result.error("用户已注册");
        }

        // 从 Redis 中获取验证码
//        String code = user.getMobile();
//        if (code == null) {
//            return Result.error("验证码不能为空");
//        }
//
//        // 从 Redis 中获取验证码对应的值
//        Object value = redisTemplate.opsForValue().get(code);
//        if (value == null) {
//            return Result.error("验证码已过期，请重新获取");
//        }

//        // 将获取到的值转换为字符串
//        String jsonString = (String) value; // 确保是字符串类型
//
//        // 使用 ObjectMapper 解析 JSON 字符串为 Map
//        ObjectMapper objectMapper = new ObjectMapper();
//        Map<String, String> map = null;
//        try {
//            map = objectMapper.readValue(jsonString, new TypeReference<Map<String, String>>() {
//            });
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException("验证码解析失败", e);
//        }
//
//        // 检查验证码是否匹配
//        if (map == null) {
//            return Result.error("验证码解析失败");
//        } else if (!map.get("code").equals(user.getCode())) {
//            return Result.error("验证码错误，请重新输入");
//        } else {
            // 创建新用户对象并设置手机号和密码
            User newUser = new User();
            newUser.setMobile(user.getMobile());
            newUser.setPassword(user.getPassword());
            newUser.setGender(0);
            newUser.setConcern(0);
            newUser.setFans(0);
            newUser.setEssay(0);

            // 插入新用户到数据库
            userMapper.insert(newUser);

            User user1 = userMapper.selectById(user.getId());

            // 返回注册成功的结果
            return Result.success(user1);
//        }
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @Override
    public int userInfoEdit(User user) {
        return userMapper.userInfoEdit(user);
    }

    /**
     * 根据id查询用户信息
     * @param id
     * @return
     */

    @Override
    public User selectUserOne(Integer id) {
        return userMapper.selectById(id);
    }

    /**
     * 根据用户id找到文章动态中间表里面的文章id，去文章表里面查询用户个人的文章
     * @param id
     * @return
     */
    @Override
    public List<Articles> selectUserArticles(Integer id) {
        List<Articles> articlesVos = userMapper.selectUserArticles(id);
        return articlesVos;
    }
    /**
     * 根据用户id找到关注中间表，查询关注的列表信息
     * @param
     * @return
     */
    @Override
    public List<User> concernList(Integer id) {
        List<User> users = userMapper.concernList(id);
        return users;
    }

    @Override
    public Result deleteConcern(Integer id,Integer userid) {
        int i = userMapper.deleteConcern(id,userid);
        if (i > 0){
            return Result.success();
        }else {
            return Result.error("取消关注失败");
        }
    }

    @Override
    public Result concern(Integer id, Integer userid) {
        int i = userMapper.concern(id, userid);
        if (i > 0){
            return Result.success();
        }else {
            return Result.error("关注失败");
        }
    }

    @Override
    public int deleteArticlesUser(Integer id) {
        return userMapper.deleteArticlesUser(id);
    };


    @Override
    public void addAlipay(String subject, String tradeNo, String outTradeNo, String totalAmount, String buyerId, String gmtPayment, String buyerPayAmount) {
        userMapper.addAlipay(subject, tradeNo, outTradeNo, totalAmount, buyerId, gmtPayment, buyerPayAmount);
    }

    @Override
    public Integer selectUseressay(Integer id) {
        return userMapper.selectUseressay(id);
    }

    @Override
    public Integer selectUserconcern(Integer id) {
        return userMapper.selectUserconcern(id);
    }

    @Override
    public Integer selectUserOnefens(Integer id) {
        return userMapper.selectUserOnefens(id);
    }

    @Override
    public Integer selectUserfavorites(Integer id) {
        return userMapper.selectUserfavorites(id);
    }

    @Override
    public Money money(Integer id) {
        return userMapper.money(id);
    }

    @Override
    public Transaction transaction(Integer id) {
        return userMapper.transaction(id);
    }

    @Override
    public Result close(Integer userid, Integer id) {
        int i = userMapper.close(userid, id);
        if (i > 0){
            return Result.success();
        }else {
            return Result.error("取消关注失败");
        }
    }

    @Override
    public List<Certified> certified( String idCard) {
        return userMapper.certified(idCard);
    }

    /**
     * 保存用户实名认证信息
     *
     * @param userid 用户ID，用于标识用户
     * @param realName 用户真实姓名，用于实名认证
     * @param idCard 用户身份证号，用于实名认证
     */
    @Override
    public void savecertified(Integer userid, String realName,String idCard) {
        // 调用userMapper的savecertified方法保存实名认证信息
        userMapper.savecertified(userid, realName,idCard);

        // 更新已认证的用户信息，通过真实姓名获取更新后的用户ID
        Integer id = userMapper.updatecertifedById(idCard);

        // 根据用户ID查询用户信息
        User user = userMapper.selectById(userid);

        // 更新用户认证状态，这里的id是通过真实姓名获取的更新后的用户ID
        userMapper.updateById(user.getId(),id);
    }

    @Override
    public Certified selectCertifiedArticles(Integer id) {
        return userMapper.selectCertifiedArticles(id);
    }

    @Override
    public ResponseEntity<Result> login(User user) {
        // 调用UserMapper中的login方法进行登录验证
        User user1 = userMapper.login(user);

        // 判断查询结果是否为空
        if (user1 != null) {
            // 生成JWT令牌
            String token = JwtUtil.getToken(user);

            // 验证JWT令牌的有效性
            if (JwtUtil.verifyToken(JwtUtil.getClaimsBody(token)) == 0) {
                // 如果令牌无效，返回未授权状态和错误信息
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Result.error("登录超时，请重新登录"));
            }

            // 创建HTTP响应头，添加授权信息
            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", "Bearer " + token);

            // 创建成功结果对象，包含生成的令牌
            Result successResult = Result.successToken(token, user1);


            // 返回带有成功结果和HTTP头的响应
            return new ResponseEntity<>(successResult, headers, HttpStatus.OK);
        }

        // 如果用户不存在，返回请求错误状态和错误信息
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Result.error("用户名或密码错误"));
    }



    @Override
    public Integer update(Integer id) {
        return userMapper.update(id);
    }


    @Override
    @Transactional
    public int addArticles(Articles articles) {
        articles.setPublishTime(new Date());
        articles.setLikeCount(0);
//        userMapper.updateEssay(articles.getUserid());
        return userMapper.addArticles(articles);
    }





}
